package com.verisette.ncos.service.support;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;

import org.apache.log4j.Logger;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerMetaData;
import org.quartz.SimpleTrigger;

import org.corp.agi.common.util.BeanContextFactory;
import com.verisette.ncos.common.ProjectConstant;

/**
 * 
 * {Description here}
 *
 * @author Pongsatorn Paolanwat(Mix)
 * @since Nov 26, 2010 10:36:10 PM
 * @version 1.0.0
 * @see
 */
public class JobManager {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(JobManager.class);

	private long runEveryInMilliseconds = 86400000; // 24*60*60*1000 = 1day 
	//private long runEveryInMilliseconds = 60*1000; 
	
	public void setRunEveryInMilliseconds(long runEveryInMilliseconds) {
		this.runEveryInMilliseconds = runEveryInMilliseconds;
	}
	
	private static String scheduleTime="";
	private SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy",Locale.US);
	private SimpleDateFormat sdfTime1 = new SimpleDateFormat("dd/MM/yyyyHH:mm:ss", Locale.US);
	
	public void manageJob() {
		logger.info("[Start manageJob()]>");
		try {
			String st = ProjectConstant.AUTO_EXPORT_START_TIME; //supportService.startImportTime();
			if (scheduleTime.equals(st)) {
				logger.info("ScheduleTime at "+scheduleTime+" isn't change.");
				return;
			}
			Date now = new Date();
			Date startDate = sdfTime1.parse(sdf1.format(now)+st);
			if (startDate.before(now)) {
				Calendar calendar = new GregorianCalendar(Locale.US);
				calendar.setTime(startDate);
				calendar.add(Calendar.DATE, 1);
				startDate = calendar.getTime();
			}
			logger.info("Change ScheduleTime from "+scheduleTime+" -----------> to "+st);
			scheduleTime = st;
	        Scheduler scheduler = (Scheduler)BeanContextFactory.getBean("schedulerFactoryBean");
	        SchedulerMetaData metaData = scheduler.getMetaData();
	        logger.debug("Executed " + metaData.numJobsExecuted() + " jobs.");
	        
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		} finally {
			logger.info("[End manageJob()]<");
		}
	}
}
